//
//  HEHomeViewController.m
//  HealthElderly
//
//  Created by 吴欧 on 2021/5/10.
//  Copyright © 2021 honglutec. All rights reserved.
//

#import "HEHomeViewController.h"
#import "XYTransitionProtocol.h"
#import "ZFScanViewController.h"
#import "ZQSearchViewController.h"
#import "HESearchData.h"
#import "HEWeatherModel.h"

#import "JFCSTableViewController.h"
#import "JFCSConfiguration.h"
#import "JFCSDataOpreation.h"
 
#import "UICollectionView+LTCollectionViewLayoutCell.h"
#import "ZLCollectionViewVerticalLayout.h"

#import "HESickedModel.h"

#import "HEFindDoctorViewController.h"
#import "HEHealthRecordViewController.h"
//#import "HEPathDispatch.h"

#import "HEOneCategViewController.h"
#import "HEFindDoctorViewController.h"
#import "HEHealthEduViewController.h"
#import "HESickbedViewController.h"
#import "HEHealthRecordViewController.h"

#import "HEHomeAdBannerCell.h"
#import "HEHomeItemCell.h"
#import "HEHomeHealthCheckCell.h"
#import "HEHealthCheckDataController.h"
#import "HEFindTeamViewController.h"
#import "HENurseViewController.h"
#import "HERecoverViewController.h"
#import "HEHomeNextCell.h"
#import "HEHealthManageViewController.h"
#import "HEServerOrgViewController.h"
#import "HEPrivateDoctorCell.h"
#import "HEDoctorInfoModel.h"
#import "HEIMInfoEntity.h"

@interface HEHomeViewController ()<QMUITextFieldDelegate, XYTransitionProtocol, BMKLocationManagerDelegate, CLLocationManagerDelegate, JFCSTableViewControllerDelegate, UICollectionViewDataSource,UICollectionViewDelegate, ZLCollectionViewBaseFlowLayoutDelegate, LTCollectionViewDynamicHeightCellLayoutDelegate, HEHomeHealthCheckCellDelegate, HESocketManagerDelegate, HEPrivateDoctorCellDelegate>

@property (nonatomic, strong) CLLocationManager *sysLocManager;
@property (nonatomic, strong) BMKLocationManager *locationManager; //定位对象
@property (nonatomic, strong) BMKLocation *courrentLoc;
@property (nonatomic, strong) NSString *selectCity;
@property (nonatomic, strong) HESearchData *searchData;

@property(nonatomic, strong) UIView *nav;

@property (nonatomic, strong) HEWeatherModel *weatherInfo;
@property (nonatomic, strong) UILabel *cityLb;
@property (nonatomic, strong) UILabel *weatherLb;


@property (nonatomic, strong) NSMutableArray <GDSectionDataModel *> *dataSource;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, assign) CGFloat cellMargin;

@property (nonatomic, strong) UILabel *titleLb;
@property (nonatomic, strong) NSMutableArray *titles;

@property (nonatomic, strong) HEDoctorInfoModel *privateModel;
@property (nonatomic, assign) BOOL isHasPrivate;
@property (nonatomic, strong) GDFiterCellModel *privateCellModel;
@property (nonatomic, strong) HEIMInfoEntity *oneIMEntity;
@end

@implementation HEHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
 
    [[HESocketManager sharedManager] addDelegate:self];

    [self initUI];
    [self initCell];
    [self defaultDeal];
}

- (void)defaultDeal {
    self.zx_navBar.hidden = YES;
    self.view.backgroundColor = CViewBgColor;
    
    [self loadUserPrivateData];

    [self requestWhenInUseAuthorization];
      
    [self refreshWeatherData];

    [self getHasRead];

    [self loadHealthRecodeData];
    
    [self loadSickData];
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
//    [[HEPathDispatch defaultDispatch] dispatchCurrentURLByExternalEvoke];
}

- (void)initUI {
    _cellMargin = 15;
    self.zx_navBar.backgroundColor = CNavBgColor;
    self.zx_navLineView.hidden = YES;
    self.zx_navTitleColor = KWhiteColor;
    self.zx_navStatusBarStyle = ZXNavStatusBarStyleLight;
    
    CGFloat offestH = kStatusBarHeight - 20;

    _nav = [UIView new];
    _nav.backgroundColor = CViewBgColor;
    [self.view addSubview:_nav];
    
    UIImageView *backView = [UIImageView new];
    backView.userInteractionEnabled = YES;
    backView.image = IMAGE_NAMED(@"home_title");
    [_nav addSubview:backView];
   
 
    // city
    UIView *weatherWarp = [UIView new];
    [backView addSubview:weatherWarp];
    UILabel *cityLb = [UILabel new];
    cityLb.text = @"定位中...";
    cityLb.textColor = KWhiteColor;
    cityLb.font = DYBlodFont(16);
    _cityLb = cityLb;
    [weatherWarp addSubview: cityLb];
    
    UITapGestureRecognizer *cityTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectCityClick)];
    [weatherWarp addGestureRecognizer:cityTap];
    UIImageView *arrow = [[UIImageView alloc] initWithImage:IMAGE_NAMED(@"arrow_down")];
    [weatherWarp addSubview: arrow];
    
    // logo
    UILabel *weatherLb = [UILabel new];
    weatherLb.text = @"";
    weatherLb.textColor = KWhiteColor;
    weatherLb.font = DYBlodFont(16);
    _weatherLb = weatherLb;
    [backView addSubview: weatherLb];
    
    // 扫一扫
    UIImageView *scan = [[UIImageView alloc] initWithImage:IMAGE_NAMED(@"home_scan")];
    scan.frame = CGRectMake(KScreenWidth - 23 - 15, 18.5 + kStatusBarHeight, 23, 23);
    [backView addSubview:scan];
    scan.userInteractionEnabled = YES;
    UITapGestureRecognizer *scanTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scanClick)];
    [scan addGestureRecognizer:scanTap];
      
    [weatherWarp mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(18.5 + kStatusBarHeight);
        make.left.equalTo(backView).offset(20);
    }];
    
    [cityLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weatherWarp);
        make.left.equalTo(weatherWarp).offset(0);
        make.bottom.equalTo(weatherWarp);
    }];
    
    [arrow mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(cityLb);
        make.left.equalTo(cityLb.mas_right).offset(3);
        make.right.equalTo(weatherWarp);
    }];
    
    [weatherLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(cityLb);
        make.left.equalTo(arrow.mas_right).offset(8);
    }];
    
    [scan mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(18.5 + kStatusBarHeight);
        make.right.equalTo(backView).offset(-20);
    }];
    
    // 输入框
    QMUITextField *searchTF = [QMUITextField new];
    [_nav addSubview:searchTF];
    searchTF.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0];
    searchTF.layer.shadowColor = [UIColor colorWithRed:13/255.0 green:98/255.0 blue:218/255.0 alpha:0.08].CGColor;
    searchTF.layer.shadowOffset = CGSizeMake(0,5);
    searchTF.layer.shadowOpacity = 1;
    searchTF.layer.shadowRadius = 6;
    searchTF.layer.cornerRadius = 22;
    searchTF.font = DYFont(16);
    
    searchTF.placeholder = @"搜疾病、视频、资讯";
    searchTF.userInteractionEnabled = YES;
    searchTF.placeholderColor = [UIColor colorWithHexString:@"#AAAAAA"];
    searchTF.delegate = self;
    
    UIView *leftWarp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 49, 18)];
    UIImageView *leftIcon = [[UIImageView alloc] initWithImage:IMAGE_NAMED(@"home_search")];
    leftIcon.frame = CGRectMake(20, 0, 18, 18);
    [leftWarp addSubview:leftIcon];
    searchTF.leftViewMode = UITextFieldViewModeAlways;
    searchTF.leftView = leftWarp;
    
    UIView *rightWarp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 49, 20)];
    UIImageView *rightIcon = [[UIImageView alloc] initWithImage:IMAGE_NAMED(@"home_scan")];
    rightIcon.frame = CGRectMake(0, 0, 20, 20);
    [rightWarp addSubview:rightIcon];
    searchTF.rightViewMode = UITextFieldViewModeAlways;
    searchTF.rightView = rightWarp;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(searchClick)];
    [searchTF addGestureRecognizer:tap];
    
//    // 扫一扫
//    rightIcon.userInteractionEnabled = YES;
//    UITapGestureRecognizer *scanTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scanClick)];
//    [rightIcon addGestureRecognizer:scanTap];
//    
 
    [_nav mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.right.equalTo(self.view);
        make.height.mas_offset(130 + offestH);
    }];
    
    [backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_nav);
        make.left.right.equalTo(_nav);
        make.height.mas_offset(97 + offestH);
    }];
    
    [searchTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_nav).offset(76 + offestH);
        make.left.equalTo(_nav).offset(15);
        make.right.equalTo(_nav).offset(-15);
        make.height.mas_offset(44);
    }];
 
    [self.view bringSubviewToFront:_nav];
    [self.view addSubview:self.collectionView];
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_nav.mas_bottom).offset(5);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }]; 
}

- (void)initCell {
    
    [self.view addSubview:self.collectionView];

    _dataSource = @[].mutableCopy;
    NSMutableArray *classArr = @[].mutableCopy;
    
    // 已签约私人医生
    GDFiterCellModel *privateModel = [GDFiterCellModel new];
    privateModel.cellKlass = HEPrivateDoctorCell.class;
    _privateCellModel = privateModel;
     
    NSMutableDictionary *params = @{}.mutableCopy;
    [params setValue:self.privateModel forKey:@"docInfo"];
    [params setValue:self.oneIMEntity == nil ? [HEIMInfoEntity new] : self.oneIMEntity forKey:@"imEntity"];
    _privateCellModel.cellData = params;
    
    // 私人医生banner
    GDFiterCellModel *privateBannerModel = [GDFiterCellModel new];
    privateBannerModel.cellKlass = HEHomeAdBannerCell.class;
    
    GDFiterCellModel *itemModel = [GDFiterCellModel new];
    itemModel.cellKlass = HEHomeItemCell.class;
    
    GDFiterCellModel *healthModel = [GDFiterCellModel new];
    healthModel.cellKlass = HEHomeHealthCheckCell.class;
    
    GDFiterCellModel *planeModel = [GDFiterCellModel new];
    planeModel.cellKlass = HEHomeNextCell.class;
       
    // 注册cell
    classArr = @[privateModel, privateBannerModel, itemModel, healthModel, planeModel].mutableCopy;
    [self.collectionView mc_registerCellByFiterModels:classArr];

    
    // 组装段落cell 填充数据
    privateBannerModel.cellData = IMAGE_NAMED(@"home_banner");
    GDSectionDataModel *sec1Model = [GDSectionDataModel new];
    if (self.isHasPrivate) {
        sec1Model.fiterCells = @[privateModel].mutableCopy;
    }else {
        sec1Model.fiterCells = @[privateBannerModel].mutableCopy;
    }
    
    GDSectionDataModel *sec2Model = [GDSectionDataModel new];
    sec2Model.cellColumn = 2;
    sec2Model.cellWidth = (KScreenWidth - (sec2Model.cellColumn + 1) * _cellMargin) / sec2Model.cellColumn;
    sec2Model.fiterCells = @[].mutableCopy;

    NSArray *serList = @[@"find_team", @"home_find_doctor"];
    for (NSString *imgStr in serList) {
        GDFiterCellModel *itemModel = [GDFiterCellModel new];
        itemModel.cellKlass = HEHomeAdBannerCell.class;
        itemModel.cellData = IMAGE_NAMED(imgStr);
        [sec2Model.fiterCells addObject:itemModel];
    }
    
    NSArray *itemImgList = @[
        @{@"name":@"护理上门", @"icon":@"home_nurse_home"},
        @{@"name":@"康复上门", @"icon":@"home_jk_health"}
    ];
    
    for (NSDictionary *dict in itemImgList) {
        GDFiterCellModel *itemModel = [GDFiterCellModel new];
        itemModel.cellKlass = HEHomeItemCell.class;
        itemModel.cellData = dict;
        [sec2Model.fiterCells addObject:itemModel];
    }
    
    // 家庭医生banner
    GDFiterCellModel *sickbedModel = [GDFiterCellModel new];
    sickbedModel.cellKlass = HEHomeAdBannerCell.class;
    sickbedModel.cellData = IMAGE_NAMED(@"sickbed");
    GDSectionDataModel *sec3Model = [GDSectionDataModel new];
    sec3Model.fiterCells = @[sickbedModel].mutableCopy;
    
    //
    GDSectionDataModel *sec4Model = [GDSectionDataModel new];
    sec4Model.fiterCells = @[healthModel].mutableCopy;
    
    [_dataSource addObject: sec1Model];
    [_dataSource addObject: sec2Model];
    [_dataSource addObject: sec3Model];
    [_dataSource addObject: sec4Model];

    [self refresh];
}
 

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        // 1.创建流水布局
        ZLCollectionViewVerticalLayout *flowLayout = [[ZLCollectionViewVerticalLayout alloc] init];
        flowLayout.delegate = self;

        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _collectionView.backgroundColor = CViewBgColor;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.alwaysBounceVertical = YES;
        
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRereshing)];
        _collectionView.mj_header = header;
 
    }
    return _collectionView;
}

- (void)refresh {
    [self.collectionView.lt_indexPathHeightCache invalidateAllHeightCache];
    [self.collectionView reloadData];
}

#pragma mark - load Data

- (void)headerRereshing {
    [self refreshWeatherData];
    [self setupWetherData];
    [self loadSickData];
    [self loadUserPrivateData];
}

- (void)loadUserPrivateData {
    __weak typeof(self) weakself = self;
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KprivateDocinfo parameters:@{} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success && response.data != nil) {
            weakself.privateModel = [HEDoctorInfoModel mj_objectWithKeyValues: response.data];
            weakself.isHasPrivate = YES;
            [self loadNewDocInfo];
        }else {
            weakself.isHasPrivate = NO;
            [self initCell];
        }

    } failure:^(NSError * _Nonnull error) {
    }];
}

- (void)loadNewDocInfo {
    HEPageRequest *req = [HEPageRequest new];
    req.pageNum = 1;
    req.pageSize = 1;
    [req addParmas:self.privateModel.user_id key:@"doctor_id"];
    
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KImInfo parameters:req success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
 
        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
        NSArray *msgList = [HEIMInfoEntity mj_objectArrayWithKeyValuesArray:response.data];
        self.oneIMEntity = msgList.firstObject;
        [self initCell];
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (void)setupWetherData {
    NSString *area = nil;
    if ([DYTools isBlankString:self.selectCity]) {
        area = [self.courrentLoc.rgcData.city removeLastStringWith:@"市"];
    }else {
        area = self.selectCity;
    }
    
    if ([DYTools isBlankString:area]) {
        [self.collectionView.mj_header endRefreshing];
        return;
    }
    
    [WOAFNetWorkingHandle GETNoHUDWithBaseUrl:KServerUrl suffixUrl:KweatherInfo parameters:@{@"area": IsNotNull(area)} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        self.weatherInfo = [HEWeatherModel mj_objectWithKeyValues: response.data];
        
        self.cityLb.text = area;
        self.weatherLb.text = [NSString stringWithFormat:@"%@%@", IsNotNull(self.weatherInfo.weather), IsNotNull(self.weatherInfo.temperature)];
        [self.collectionView.mj_header endRefreshing];
    } failure:^(NSError * _Nonnull error) {
        [self.collectionView.mj_header endRefreshing];
    }];
}

// 获取是否有未读
- (void)getHasRead {
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KunReadMsg parameters:@{} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            NSNumber *sys_num = (NSNumber *)response.data[@"system_message"];
            NSNumber *ask_num = (NSNumber *)response.data[@"ask_message"];

            NSInteger sysInfoNum = sys_num.integerValue;
            NSInteger askInfoNum = ask_num.integerValue;
            
            UITabBarItem *msgTabbar = self.navigationController.tabBarController.viewControllers[1].tabBarItem;

            if ((sysInfoNum + askInfoNum) > 0) {
                [msgTabbar pp_setBadgeHeight:16];
                [msgTabbar pp_moveBadgeWithX: 3 Y: 5];
                msgTabbar.badgeView.font = DYBlodFont(14);

                msgTabbar.badgeView.qmui_borderPosition = QMUIViewBorderPositionBottom | QMUIViewBorderPositionTop | QMUIViewBorderPositionLeft | QMUIViewBorderPositionRight;
                msgTabbar.badgeView.qmui_borderWidth = 2;
                msgTabbar.badgeView.qmui_borderColor = KWhiteColor;
            }else {

                [msgTabbar pp_hiddenBadge];
            }
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

/// 获取实名数据
- (void)loadHealthRecodeData {
    KWeakSelf
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KgetPhrUserInfo parameters:@{} success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            [UserManager sharedUserManager].archiveInfo = [HEHealthArchiveModel mj_objectWithKeyValues: response.data];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (void)loadSickData {
    KWeakSelf
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KSickedNext parameters:@{@"number" : @3} success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            [self initCell];
            
            NSArray *arr = [HESickedPlanModel mj_objectArrayWithKeyValuesArray:response.data];
            if (arr.count > 0) {
              
                GDFiterCellModel *planeModel = [GDFiterCellModel new];
                planeModel.cellKlass = HEHomeNextCell.class;
                planeModel.cellData = arr;
                
                GDSectionDataModel *sec5Model = [GDSectionDataModel new];
                sec5Model.fiterCells = @[planeModel].mutableCopy;
                
                [self.dataSource addObject:sec5Model];
            }
        }
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
    } failure:^(NSError * _Nonnull error) {
        [self.collectionView.mj_header endRefreshing];
    }];
}

#pragma mark - click
- (void)scanClick {
    ZFScanViewController *vc = [ZFScanViewController new];
    [self.navigationController pushViewController:vc animated:YES];
    
    vc.returnScanBarCodeValue = ^(NSString *barCodeString) {
        DLog(@"sacn  %@", barCodeString)
         
    };
}
 
- (void)searchClick {
    self.searchData = [HESearchData new];
    self.searchData.superVC = self;
    [self.searchData toSearchVC];
}

- (void)selectCityClick {
    JFCSConfiguration *config = [[JFCSConfiguration alloc] init];
    config.hideAreaSwitchButton = YES;
    JFCSTableViewController *vc = [[JFCSTableViewController alloc] initWithConfiguration:config delegate:self];
    [self.navigationController pushViewController:vc animated:YES];
}

 
#pragma mark - 单次定位
- (void)getCurrentLocal {
    [self.locationManager requestLocationWithReGeocode:YES withNetworkState:YES completionBlock:^(BMKLocation * _Nullable location, BMKLocationNetworkState state, NSError * _Nullable error) {
        if (error) {
            [self.collectionView.mj_header endRefreshing];
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
        }
       if (location) {//得到定位信息，添加annotation
           self.courrentLoc = location;
            if (location.location) {
                [UserManager sharedUserManager].currentCoordinate = location.location.coordinate;
            }
            if (location.rgcData) {
                [self setupWetherData];
            }
        }
    }];
}

- (void)refreshWeatherData {
    [self getCurrentLocal];
}

#pragma mark - 转场
- (UIView *)targetTransitionView{
    return _nav;
}
- (BOOL)isNeedTransition{
    return YES;
}

#pragma mark - 定位权限

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (status == kCLAuthorizationStatusAuthorizedAlways ||
        status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        [self refreshWeatherData];
    }
}

-(void)requestWhenInUseAuthorization {
    if (![self getUserLocationAuth]) {
         if ([self.sysLocManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [self.sysLocManager requestWhenInUseAuthorization];
        }
    }
}
 
- (BOOL)getUserLocationAuth {
    BOOL result = NO;
    switch ([CLLocationManager authorizationStatus]) {
        case kCLAuthorizationStatusNotDetermined: //用户没有选择是否要使用定位服务（弹框没选择，或者根本没有弹框）
            break;
        case kCLAuthorizationStatusRestricted: //定位服务授权状态受限制，可能由于活动限制了定位服务，并且用户不能改变当前的权限，这个状态有可能不是用户拒绝的，但是也有可能是用户拒绝的
            break;
        case kCLAuthorizationStatusDenied: //用户在设置中关闭定位功能，或者用户明确的在弹框之后选择禁止定位
            [Dialog toastBottom:@"请前往设置开启定位权限~"];
            break;
        case kCLAuthorizationStatusAuthorizedAlways:
            result = YES;
            break;
        case kCLAuthorizationStatusAuthorizedWhenInUse:
            result = YES;
            break;
            
        default:
            break;
    }
    return result;
}

#pragma mark - 地区天气选择 JFCSTableViewControllerDelegate
- (void)viewController:(JFCSTableViewController *)viewController didSelectCity:(JFCSBaseInfoModel *)model {
    self.selectCity = model.name;
    [self setupWetherData];
}

#pragma mark - HESocketManagerDelegate \ HEPrivateDoctorCellDelegate
- (void)onRecvMessages:(HEIMMessageModel *)message {
    if (message.message.modelType == HEIMUserModelTypeIM) {
        [self loadNewDocInfo];
    }
}

- (void)cellWithPrivateIMRefresh {
    [self loadNewDocInfo];
}

#pragma mark - ZLCollectionViewBaseFlowLayoutDelegate
//指定section用的样式。LabelLayout是标签样式，ClosedLayout用于tableviewcell或者瀑布流，九宫格之类的。
- (ZLLayoutType)collectionView:(UICollectionView *)collectionView layout:(ZLCollectionViewBaseFlowLayout *)collectionViewLayout typeOfLayout:(NSInteger)section {
    return ClosedLayout;
}

//如果是ClosedLayout样式的section，必须实现该代理，指定列数
- (NSInteger)collectionView:(UICollectionView *)collectionView layout:(ZLCollectionViewBaseFlowLayout *)collectionViewLayout columnCountOfSection:(NSInteger)section {
    GDSectionDataModel *secModel = _dataSource[section];
    return secModel.cellColumn;
}

#pragma mark UICollectionViewDataSource
#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return _dataSource.count;
}

// 每个分区上得元素个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    GDSectionDataModel *secModel = _dataSource[section];
    return secModel.fiterCells.count;
}

// 设置cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    GDSectionDataModel *secModel = _dataSource[indexPath.section];
    GDFiterCellModel *model = secModel.fiterCells[indexPath.row];
    MCCollectionBaseCell *cell = [collectionView mc_dequeueReusableCellWithFiterModel:model forIndexPath:indexPath];
    cell.proxyVC = self;
    [cell configCellWithFiterModel:model indexPath:indexPath];
    return cell;
}

// 设置cell大小 itemSize：可以给每一个cell指定不同的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    GDSectionDataModel *secModel = _dataSource[indexPath.section];
    GDFiterCellModel *model = secModel.fiterCells[indexPath.row];
    CGFloat cellHeight = [collectionView lt_heightForCellWithIdentifier:model.cellId fixedWidth:secModel.cellWidth cacheByIndexPath:indexPath configuration:^(MCCollectionBaseCell *cell) {
        [cell configCellWithFiterModel:model indexPath:indexPath];
    }];
    return CGSizeMake(secModel.cellWidth, cellHeight);
}


// 设置UIcollectionView整体的内边距（这样item不贴边显示）
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    // 上 左 下 右
    return UIEdgeInsetsMake(0, _cellMargin , 10, _cellMargin);
}

// 设置minimumLineSpacing：cell上下之间最小的距离
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return _cellMargin;
}

// 设置minimumInteritemSpacing：cell左右之间最小的距离
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return _cellMargin;
}
 
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    GDSectionDataModel *secModel = _dataSource[indexPath.section];
    GDFiterCellModel *model = secModel.fiterCells[indexPath.row];
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            HEServerOrgViewController *vc = [HEServerOrgViewController new];
            vc.type = HEServerOrgTypeDoctor;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            HEServerOrgViewController *vc = [HEServerOrgViewController new];
            vc.type = HEServerOrgTypeTeam;
            [self.navigationController pushViewController:vc animated:YES];
        }
        else if (indexPath.row == 1) {
            HEServerOrgViewController *vc = [HEServerOrgViewController new];
            vc.type = HEServerOrgTypeDoctor;
            [self.navigationController pushViewController:vc animated:YES];
        }
        else if (indexPath.row == 2) {
            HENurseViewController *vc = [HENurseViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
        else if (indexPath.row == 3) {
            HERecoverViewController *vc = [HERecoverViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }else if (indexPath.section == 2) {
        [self toSickedVCWithVaildRealClick];
    }
}

- (void)toSickedVCWithVaildRealClick {
   if (![[UserManager sharedUserManager] getUserInfo].verifyStatus) {
       HERealNameAuthAlterController *vc = [HERealNameAuthAlterController new];
       [self.view addSubview:vc.view];
   }else {
       HESickbedViewController *vc = [HESickbedViewController new];
       [self.navigationController pushViewController:vc animated:YES];
   }
}
 
#pragma mark - HEHomeHealthCheckCellDelegate
- (void)healthChcekCellAllHandler {
    HEHealthManageViewController *vc = [HEHealthManageViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)healthChcekCellTapHandler:(NSInteger)index {
    HEHealthCheckDataController *vc = [HEHealthCheckDataController new];
    vc.index = index;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - lazyLoad

- (BMKLocationManager *)locationManager {
    if (!_locationManager) {
        //初始化BMKLocationManager类的实例
        _locationManager = [[BMKLocationManager alloc] init];
        //设置定位管理类实例的代理
        _locationManager.delegate = self;
        //设定定位坐标系类型，默认为 BMKLocationCoordinateTypeGCJ02
        _locationManager.coordinateType = BMKLocationCoordinateTypeBMK09LL;
        //设定定位精度，默认为 kCLLocationAccuracyBest
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        //设定定位类型，默认为 CLActivityTypeAutomotiveNavigation
        _locationManager.activityType = CLActivityTypeAutomotiveNavigation;
        //指定定位是否会被系统自动暂停，默认为NO
        _locationManager.pausesLocationUpdatesAutomatically = NO;
        /**
         是否允许后台定位，默认为NO。只在iOS 9.0及之后起作用。
         设置为YES的时候必须保证 Background Modes 中的 Location updates 处于选中状态，否则会抛出异常。
         由于iOS系统限制，需要在定位未开始之前或定位停止之后，修改该属性的值才会有效果。
         */
        _locationManager.allowsBackgroundLocationUpdates = NO;
        /**
         指定单次定位超时时间,默认为10s，最小值是2s。注意单次定位请求前设置。
         注意: 单次定位超时时间从确定了定位权限(非kCLAuthorizationStatusNotDetermined状态)
         后开始计算。
         */
        _locationManager.locationTimeout = 10;
    }
    return _locationManager;
}

- (CLLocationManager *)sysLocManager {
    if (!_sysLocManager) {
        _sysLocManager = [[CLLocationManager alloc] init];
        _sysLocManager.desiredAccuracy = kCLLocationAccuracyBest;
        _sysLocManager.distanceFilter = kCLLocationAccuracyHundredMeters;
        _sysLocManager.delegate = self;
    }
    return _sysLocManager;
}

@end
